'use client';

import { Button } from '@/components/ui/Button';
import { trpcPureClient } from '@/utils/api';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Plus } from 'lucide-react';
import Link from 'next/link';
import { use, useState } from 'react';

export default function StoragePage({
  params,
}: {
  params: Promise<{
    id: string;
  }>;
}) {
  const { id } = use(params);
  const [queryClient] = useState(useQueryClient());
  const { data: storages } = useQuery({
    queryKey: ['storages'],
    queryFn: async () => {
      return trpcPureClient.storages.listStorages.query();
    },
  });

  const { mutate: changeStorage } = useMutation({
    mutationFn: trpcPureClient.apps.changeStorage.mutate,
    onSuccess(data, { appId, storageId }) {
      queryClient.setQueryData(['apps'], (oldData: typeof apps) => {
        if (!oldData) return oldData;

        return oldData.map((app) => {
          if (app.id !== appId) return app;

          app.storageId = storageId;
          return app;
        });
      });
    },
  });

  const { data: apps } = useQuery({
    queryKey: ['apps'],
    queryFn: async () => {
      return trpcPureClient.apps.listApps.query();
    },
  });

  const currentApp = apps?.find((app) => app.id === id);

  return (
    <div className="container pt-10 mx-auto">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl mb-6">Storage</h1>
        <Button asChild>
          <Link href={`/dashboard/apps/${id}/storage/new`}>
            <Plus />
          </Link>
        </Button>
      </div>
      {storages?.map((storage) => {
        return (
          <div
            key={storage.id}
            className="border p-4 flex justify-between items-center"
          >
            <span>{storage.name}</span>
            <Button
              disabled={currentApp?.storageId === storage.id}
              onClick={() =>
                changeStorage({ appId: id, storageId: storage.id })
              }
            >
              {currentApp?.storageId === storage.id ? 'Used' : 'Use As Default'}
            </Button>
          </div>
        );
      })}
    </div>
  );
}
